<template>
  <el-drawer
    ref="drawerBox"
    :visible.sync="drawerVisible"
    :close-on-press-escape="false"
    :title="element.name"
    :size="showMobilePage ? '100%' : '80%'"
    append-to-body
    @close="closeDialog"
  >
    <div class="drawer-content">
      <FilterInput
        ref="FilterToolRef"
        v-model="paramsObj"
        :filter-list="filterList"
        show-search-btn
        line-feed
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"
        @filterTagStatus="filterTagStatus"
      />
      <el-tabs v-model="curTabName" style="margin: 17px 0 8px" @tab-click="onSubActiveOrderChange">
        <el-tab-pane label="列表" name="all"/>
        <el-tab-pane name="selected">
          <span slot="label">已选择<el-badge v-if="selectedData.length" :value="selectedData.length" /></span>
        </el-tab-pane>
      </el-tabs>
      <div class="table-list">
        <div v-loading="listLoading">
          <template v-if="(isAllTab && list.item.list && list.item.list.length > 0) || (isSelectedTab && selectedData.length > 0)">
            <el-table
              ref="linkTableRef"
              :data="isAllTab?list.item.list:selectedTableData"
              :row-class-name="(data) => tableRowClassName(data)"
              :height="setTableHeight"
              class="fb-table"
              header-cell-class-name="order-data-header-cell"
              element-loading-text="加载中..."
              empty-text="暂无数据"
              fit
              select-callback
              hightlight-current-rowref="tableRef"
              @select="selectTable"
              @select-all="selectTable"
              @sort-change="sortMethod">
              <el-table-column align="center" type="selection" fixed="left" width="50" />
              <template v-for="field in list.item.field">
                <el-table-column
                  :key="field.key"
                  :label="field.fieldName"
                  :prop="field.key"
                  :sortable="field.isSort && 'custom'"
                  align="left"
                  min-width="150">
                  <template slot-scope="scope">
                    <StatusText
                      v-if="field.key === 'status'"
                      :color="['#FFBC3D','#FD8546', '#FF4E5F', '#999', '#31CC9C','#406EFF'][scope.row.status]"
                      :text="scope.row.status | processCommonStatus" />
                    <!--流水号支持跳转-->
                    <template v-else-if="field.type === 'workflowId' ">
                      <ToolTip :content="scope.row.content[field.key]" is-can-click @handelClick="toDetail(scope.row)" />
                    </template>
                    <!-- 链接 -->
                    <template v-else-if="field.type === 'link'">
                      <LinkElement
                        v-if="scope.row.content && scope.row.content[field.key]"
                        :link="scope.row.content[field.key]"
                        :link-name="field.defaultLinkName" />
                      <div v-else>--</div>
                    </template>
                    <ToolTip v-else-if="scope.row.content && scope.row.content[field.key]" :content="handelValue(field, scope.row.content[field.key])" />
                    <div v-else>--</div>
                  </template>
                </el-table-column>
              </template>
            </el-table>
          </template>
          <EmptyPlaceholder v-else empty-text="暂无数据" is-border />
        </div>
        <fixed-pagination class="bottom-pagination">
          <div class="delete-button-container">
            <el-button :disabled="!hasSeleted" size="small" type="primary" class="related-btn" @click="confirm">关联</el-button>
            <el-button size="small" plain type="primary" class="related-btn" @click="closeDialog">关闭</el-button>
          </div>
          <el-pagination
            v-show="(isAllTab && list.total > 0) || (isSelectedTab && selectedData.length > 0)"
            :current-page="isAllTab?list.page:selectedPage"
            :page-size="isAllTab?list.perPage:selectedPerPage"
            :total="isAllTab?list.total:selectedData.length"
            :page-sizes="[20, 50, 100, 250, 500]"
            :layout="layout"
            :small="showMobilePage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </fixed-pagination>
      </div>
    </div>
  </el-drawer>
</template>

<script>
// api
import { getApprovalTemplate, getCommonApprovalList, getCommonApprovalFilterList } from '@/api/approvalModule';
import { getDepartmentAll } from '@/api/config';
// mixins
import tableSelections from '@/mixins/tableSelections';
import TableAdaptive from '@/mixins/tableAdaptive';
import { processCommonStatus } from '@/filters/status';
// components
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import FilterInput from '@/components/Tool/filter';
import LinkElement from '@/views/legal/process/components/formMake/components/linkElement';
import filterFun from '@/views/approvalModule/mixins/filterFun';
import math from '@/utils/math';
import { mapState } from 'vuex';

export default {
  name: 'RelatedLinkForm',
  components: {
    FilterInput, EmptyPlaceholder, LinkElement
  },
  filters: { processCommonStatus },
  mixins: [tableSelections, TableAdaptive, filterFun],
  props: {
    element: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      paramsObj: {},
      advancedOptions: {}, // 高级设置
      drawerVisible: false,
      page: 1,
      perPage: 20,
      list: {
        item: {
          field: [],
          list: []
        },
        page: 1,
        perPage: 20,
        total: 0
      },
      selectedPage: 1,
      selectedPerPage: 20,
      sortType: '',
      sortName: '',
      listLoading: false,
      idKey: 'id', // 多选框参数
      tableRefName: 'linkTableRef',
      curTabName: 'all',
      selectedData: [],
      cancelToken: null,
      tableOutsideHeight: 223,
      filterList: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    isAllTab() {
      return this.curTabName === 'all';
    },
    isSelectedTab() {
      return this.curTabName === 'selected';
    },
    hasSeleted() {
      return this.multipleSelectionAll.length > 0;
    },
    selectedTableData() {
      return this.selectedData.slice((this.selectedPage - 1) * this.selectedPerPage, this.selectedPage * this.selectedPerPage);
    },
    moduleId() {
      if (this.element && this.element.options && this.element.options.remoteParams) {
        return this.element.options.remoteParams.workFlowId || this.element.options.remoteParams.id;
      }
      return '';
    },
    layout() {
      return this.showMobilePage ? 'total, prev, next' : 'total, prev, pager, next, sizes,jumper';
    }
  },
  methods: {
    // 初始获取数据
    oepnDialog(data = []) {
      this.drawerVisible = true;
      this.selectedData = data || [];
      this.multipleSelectionAll = data || [];
      this.curTabName = 'all';
      this.getTemplate();
      this.queryFilterList();
      this.fetchData();
    },
    closeDialog() {
      this.drawerVisible = false;
    },
    // fitter
    queryClick() {
      if (this.isSelectedTab) this.curTabName = 'all';
      this.fetchData(true);
    },
    queryEmpty() {
      this.sortType = '';
      this.sortName = '';
      this.paramsObj = {};
      this.queryClick();
    },
    // 翻页
    handleData(tableData) {
      return tableData.slice((this.selectedPage - 1) * this.selectedPerPage, this.selectedPage * this.selectedPerPage);
    },
    handleSizeChange(val) {
      if (this.curTabName === 'all') {
        this.perPage = val;
        this.fetchData(true);
      } else if (this.isSelectedTab) {
        this.selectedPerPage = val;
        this.setSelectRow(this.selectedTableData);
      }
    },
    handleCurrentChange(toPage) {
      if (this.curTabName === 'all') {
        this.page = toPage;
        this.fetchData();
      } else if (this.isSelectedTab) {
        this.selectedPage = toPage;
        this.setSelectRow(this.selectedTableData);
      }
    },
    // 获取列表数据
    fetchData(reset = false) {
      this.listLoading = true;
      if (reset) this.page = 1;
      const params = this.formatParams();
      params.fromProcess = 1;
      if (this.element.options.presetFilterParams) {
        // const presetFilter = this.setDynamicFilter(this.element.options.presetFilter);
        params.presetFilter = this.element.options.presetFilterParams;
      }
      getCommonApprovalList(params).then(res => {
        this.listLoading = false;
        if (res.code === 200 && res.data && res.data.item) {
          this.list = res.data;
          this.setSelectRow(res.data.item.list);
        }
        this.listLoading = false;
      }).catch(_ => {
        this.listLoading = false;
      });
    },
    getTemplate() {
      const moduleId = this.moduleId;
      getApprovalTemplate({ id: moduleId }).then(res => {
        if (res.code === 200) {
          this.advancedOptions = res.data.advancedOptions;
        }
      }).catch(() => {
      });
    },
    // 关联
    confirm() {
      const data = this.selectedData;
      this.$emit('confirm', data);
      this.closeDialog();
    },
    // 切换列表tab
    onSubActiveOrderChange(data) {
      if (data.paneName === 'all') {
        this.fetchData();
      }
      if (this.isSelectedTab) this.setSelectRow(this.selectedTableData);
    },
    // 保留数据
    tableSelectionChange(selection) {
      this.selectedData = selection;
      if (this.isSelectedTab) this.setSelectRow(this.selectedTableData);
    },
    /**
     *  筛选
     */
    async queryFilterList() {
      try {
        const deptResult = await getDepartmentAll() || {};
        this.deptTreeList = deptResult.data || [];
        const moduleId = this.moduleId;
        const filterData = await getCommonApprovalFilterList(moduleId) || {};
        this.filterList = this.setFilterList(filterData.data || []);
        this.$nextTick(() => {
          this.$refs['FilterToolRef'] && this.$refs['FilterToolRef'].changeSelectKey();
        });
      } catch (e) {
        console.log(e);
        return false;
      }
    },
    formatParams() {
      const params = this.setDynamicFilter();
      params.id = this.moduleId;
      params.sortName = this.sortName || '';
      params.sortType = this.sortType || '';
      params.page = this.page;
      params.perPage = this.perPage;
      return params;
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.fetchData();
    },
    toDetail(rowData) {
      const routeUrl = this.$router.resolve({
        name: 'approvalModuleDetail',
        params: { moduleId: this.moduleId },
        query: { id: rowData.id, processId: rowData.processId }
      });
      window.open(routeUrl.href, '_blank');
    },
    handelValue(field, value) {
      if (!value || !field.options) {
        if (field.type === 'input' && field.isNumber && field.isShowPercentage && typeof value === 'number') {
          return math.multiply(value, 100) + '%';
        }
        return value;
      }
      const isNumberFormula = field.type === 'formulaInput' && !field.options.modeType;
      if (value && field.options && isNumberFormula || (field.type === 'input' && field.options.dataType === 'number')) {
        const precision = field.options.precision;
        if (precision || precision === 0) {
          return Number(Number(value).toFixed(precision));
        }
      }
      return value;
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-drawer__header {
  height: 48px;
  padding: 0 12px 0 24px;
  margin: 0;
  box-shadow: 2px 4px 5px 0 rgba(221,225,234,0.3);
  display: flex;
  align-items: center;
  > span {
    font-size: 14px;
    color: #333;
  }
  ::v-deep .el-tabs__nav-wrap::after {
    height: 0 !important;
  }
}
::v-deep .el-tabs__header {
  margin: 0;
  border: none;
}
::v-deep .el-drawer__body {
  overflow-y: auto;
  margin-bottom: 56px;
}
::v-deep .el-drawer__header>span{
  font-size: 16px;
}
::v-deep .el-badge__content{
  background: #FB5227;
}
::v-deep .el-badge__content{
  margin-top: 18px;
}
.tip {
  color: #999;
  font-size: 13px;
  margin-left: 20px;;
}
.drawer-content {
  padding: 22px 24px 0;
  overflow-y: auto;
  .table-list {
    border-radius: 10px;
    .el-row {
      padding: 0;
    }
    .delete-button-container {
      flex:1;
      height: 32px;
      display: flex;
      align-items: center;
      .related-btn {
        margin-left: 20px;
        padding-left: 12px;
        padding-right: 12px;
      }
    }
    ::v-deep .pagination-flex {
      position: absolute;
      width: 100% !important;
    }
  }
}
::v-deep .el-tabs__nav-wrap::after {
  z-index: -1;
}
::v-deep .el-tabs__active-bar {
  bottom: 1px;
}
</style>
